﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mindfor.Web.Data;
using Mindfor.Web.Routing;
using NHibernate;
using NHibernate.Linq;
using Mindfor.Web.Models;
using Mindfor.Web.Features;

namespace Mindfor.Web.Modules.Vacancies.Controllers
{
	public class VacanciesController : CmsController
	{
		/// <summary>
		/// Returns PageResult which renders Vacancy user-index view.
		/// </summary>
		/// <param name="page">Page number.</param>
		/// <returns>PageResult.</returns>
		[UrlRoute(1, "")]
		[UrlRouteDefault(1, "page", 1)]
		[UrlRoute(2, "Page{page}")]
		[UrlRouteConstraint(2, "page", Constraints.IsInt)]
		public ActionResult Index(int page)
		{
			// get vacancy items
			int pageIndex = page - 1;
			if (pageIndex < 0)
				return HttpNotFound();
			int pageSize = Module.Options[VacanciesModule.IndexPageSizeOption].GetValue<int>();

			IQueryable<Vacancy> vacQuery = Data.Query<Vacancy>()
				.OrderByDescending(r => r.Id);

			ViewData.Model = vacQuery.Skip(pageIndex * pageSize).Take(pageSize).ToList();
			ViewData["Pager"] = new PagerModel(vacQuery.Count(), pageSize);
			ViewData["IsEditable"] = User != null && User.IsInRole(CmsRoles.Administrator, VacanciesModule.VacanciesRole);

			return View();
		}


		/// <summary>
		/// Returns PageResult which renders Vacancy admin-index view.
		/// </summary>
		/// <param name="page">Page number.</param>
		/// <returns>PageResult.</returns>
		[UrlRoute(1, "", Path="Admin/Vacancies")]
		[UrlRouteDefault(1, "page", 1)]
		[UrlRoute(2, "Page{page}", Path="Admin/Vacancies")]
		[UrlRouteConstraint(2, "page", Constraints.IsInt)]
		[AdminLink("Вакансии", "Сайт")]
		[CmsAuthorize(VacanciesModule.VacanciesRole)]
		public ActionResult IndexAdmin(int page)
		{
			// get feedback items
			int pageSize = 20;
			int pageIndex = page - 1;
			if (pageIndex < 0)
				return HttpNotFound();

			IQueryable<Vacancy> vacQuery = Data.Query<Vacancy>().OrderByDescending(r => r.Id);

			ViewData.Model = vacQuery.Skip(pageIndex * pageSize).Take(pageSize).ToList();
			ViewData["Pager"] = new PagerModel(vacQuery.Count(), pageSize);

			return View();
		}

		/// <summary>
		/// New vacancy creating page.
		/// </summary>
		[HttpGet]
		[CmsAuthorize(VacanciesModule.VacanciesRole)]
		[UrlSubAction("IndexAdmin")]
		[UrlRoute("Add", Path="Admin/Vacancies")]
		[LoadModelState]
		[ReturnUrlEnable]
		public ActionResult Add()
		{
			return Edit(null);
		}

		/// <summary>
		/// News vacancy creating 'POST'-method.
		/// </summary>
		[HttpPost]
		[ValidateInput(false)]
		public ActionResult Add(Vacancy model)
		{
			return Edit(null, model);
		}

		/// <summary>
		/// Vacancy item editing page.
		/// </summary>
		[HttpGet]
		[UrlRoute("{id}/Edit", Path="Admin/Vacancies")]
		[UrlRouteConstraint("id", Constraints.IsInt)]
		[UrlSubAction("IndexAdmin")]
		[CmsAuthorize(VacanciesModule.VacanciesRole)]
		[LoadModelState]
		[ReturnUrlEnable]
		public ActionResult Edit(int? id)
		{
			Vacancy item;
			// get item
			if (id.HasValue)
			{
				item = Data.Get<Vacancy>(id.Value);
				if (item == null)
					return HttpNotFound();
			}
			else
			{
				item = new Vacancy();
				item.Recruiter = Module.Options[VacanciesModule.DefaultRecruiterOption].GetValue<string>();
				item.RecruiterPhone = Module.Options[VacanciesModule.DefaultRecruiterPhoneOption].GetValue<string>();
				item.RecruiterEmail = Module.Options[VacanciesModule.DefaultRecruiterEmailOption].GetValue<string>();
			}

			ViewData.Model = item;
			return View("Edit");
		}

		/// <summary>
		/// Vacancy item editing 'POST'-method.
		/// </summary>
		[HttpPost]
		[CmsAuthorize(VacanciesModule.VacanciesRole)]
		[ValidateInput(false)]
		public ActionResult Edit(int? id, Vacancy model)
		{
			// is model is valid
			if (ModelState.IsValid)
			{
				model = Data.MergeEntity(model);
				if (id.HasValue && model.Id != id.Value)
					return HttpNotFound();

				// typograf texts
				model.Description = Typograf.ProcessText(model.Description, TypografEntityTypes.HtmlEntities);

				// submit changes
				using (ITransaction t = Data.BeginTransaction())
				{
					Data.SaveOrUpdate(model);
					t.Commit();
				}

				return RedirectToAction("Index");
			}
			this.SaveModelState();
			return RedirectToAction(id == null ? "Add" : "Edit");
		}

		/// <summary>
		/// Delete vacancy.
		/// </summary>
		/// <param name="id">Vacancy item id.</param>
		[HttpGet]
		[UrlSubAction("IndexAdmin")]
		[UrlRoute("{id}/Delete", Path="Admin/Vacancies")]
		[UrlRouteConstraint("id", Constraints.IsInt)]
		[CmsAuthorize(VacanciesModule.VacanciesRole)]
		[ReturnUrlEnable]
		public ActionResult Delete(int id)
		{
			// get news
			Vacancy item = Data.Get<Vacancy>(id);
			if (item == null)
				return HttpNotFound();

			// delete
			using (ITransaction t = Data.BeginTransaction())
			{
				Data.Delete(item);
				t.Commit();
			}

			// return
			return RedirectToAction("Index");
		}
	}
}